package socketing;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.*;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
//out有错误　不要用了
public class V1Client {
    public static void main(String[] args) throws IOException {

//        socket.setKeepAlive(true);
        Socket socket = new Socket("master", 4444);

        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(
                        socket.getOutputStream(), StandardCharsets.UTF_8));
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(
                        socket.getInputStream(), StandardCharsets.UTF_8));

        Scanner scanner = new Scanner(System.in);
        new Thread(()->{
            final BufferedReader readerl= reader;
            while (true){
                try {
                    String s = readerl.readLine();
                    Tool.debug("res: "+s);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        },"receive处理专用线路").start();
        while (true){
            String req = scanner.nextLine();
            if (req.equals("quit"))break;
            Tool.debug(req);
            writer.write(req);
            writer.newLine();
            writer.flush();
        }
        reader.close();
        writer.close();
        socket.close();

    }

    public static void send(String url, String data, Consumer<String> callback,Socket socket) throws IOException {
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(
                        socket.getOutputStream(), StandardCharsets.UTF_8));
        Runnable toSend = ()->{
            try {
                writer.write(url+" : "+data);
                writer.newLine();
                Thread.sleep(1000);
                writer.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }
        };
        sender.execute(toSend);

        receiver.execute(()->{
            try {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(
                                socket.getInputStream(),StandardCharsets.UTF_8));
                while (!socket.isClosed()){
                    String s = reader.readLine();
//                    sub.accept(s);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        });


    }
//    public static final ReentrantLock lock = new ReentrantLock();
//    public static final Condition tag = lock.newCondition();
    public static final Map<String,Socket> sockets= new ConcurrentHashMap<String,Socket>();
    public static final CopyOnWriteArrayList tasks = new CopyOnWriteArrayList();
    public static final Executor sender =Executors.newSingleThreadExecutor();
    public static final Executor receiver =Executors.newSingleThreadExecutor();
    public static Socket connect(String host, int port) throws IOException {
        Socket socket;
        socket= new Socket(host, port);
        sockets.put(host+port,socket);
        return socket;

    }
    public static void mainSend(String url) throws IOException {
        System.out.println(url +" ==>>> master:4444/path");
        String kurl="master:4444/path";
        String[] s1 = kurl.split(":");
        String[] s2 = s1[1].split("/");
        Socket socket = connect(s1[0]
                ,Integer.parseInt(s2[0]));

        Scanner scanner = new Scanner(System.in);
        while (true){
            String data = scanner.nextLine();
            if (data.equals("quit"))break;

            //   ajax 请求
            Tool.debug("前端将要发送消息　"+data);
            send(s2[1],
                    data,

                    (res)->{
                Tool.debug("前端接收并处理了　"+res);
            },socket);

        }
        disconnect(s1[0]
                ,Integer.parseInt(s2[0]));

    }

    public static void maind(String[] args) {
        try {
            mainSend("hihih");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void disconnect(String host, int port) throws IOException {
        Socket socket = sockets.get(host + port);
        sockets.remove(socket);

        socket.getInputStream().close();
        socket.getOutputStream().close();
        socket.close();
    }

    class Task{
        private Socket socket;
        private Consumer<String> consumer;

        public Task(Socket socket, Consumer<String> consumer) {
            this.socket = socket;
            this.consumer = consumer;
        }
    }
}
